//
//  XMPikerView.m
//  BigJoy
//
//  Created by Rowling on 2017/7/4.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "XMPikerView.h"

@interface XMPikerView() <UIPickerViewDelegate,UIPickerViewDataSource>
{
    
    NSMutableArray *yearArray;
    NSArray *monthArray;
    NSMutableArray *monthMutableArray;
    NSMutableArray *DaysMutableArray;
    NSMutableArray *DaysArray;
    NSString *currentMonthString;
    
    NSInteger selectedYearRow;
    NSInteger selectedMonthRow;
    NSInteger selectedDayRow;
    
    BOOL firstTimeLoad;
    
    NSInteger m ;
    int year;
    int month;
    int day;
    
}
@property (nonatomic,strong) UIPickerView *customPicker;

@end

@implementation XMPikerView

-(instancetype)initWithFrame:(CGRect)frame AndType:(pickerType)type {
    if(self = [super initWithFrame:frame]) {
        [self setUI];
    }
    return self;
}

-(void)setUI {
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    UIButton * bottmView = [UIButton new];
    // 整个bottmview是个button，因为懒得去实现touchBegin。
    bottmView.backgroundColor = [UIColor whiteColor];
    [self addSubview:bottmView];
    [bottmView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self);
        make.height.equalTo(@200);
    }];
    
    UIView * headView = [[UIView alloc]init];
    [bottmView addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(bottmView);
        make.height.equalTo(@50);
    }];
    // cancelButton
    UIButton * btn = [[UIButton alloc]init];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [headView addSubview:btn];
    [btn sizeToFit];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headView);
        make.left.equalTo(headView).offset(15);
    }];
    
    //okButton
    UIButton * okbtn = [UIButton new];
    [okbtn setTitle:@"确定" forState:normal];
    okbtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [okbtn setTitleColor:[UIColor colorForHex:@"f54645"] forState:UIControlStateNormal];
    [okbtn sizeToFit];
    [headView addSubview:okbtn];
    [okbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headView).offset(-15);
        make.centerY.equalTo(headView);
    }];
    // lineView
    UIView * lineView = [UIView new];
    [headView addSubview:lineView];
    lineView.backgroundColor = XMColor(220, 220, 220);
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(headView);
        make.height.equalTo(@1);
    }];
    self.customPicker = [UIPickerView new];
    [bottmView addSubview:self.customPicker];
    [self.customPicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.left.equalTo(bottmView);
        make.top.equalTo(headView.mas_bottom);
    }];
    [self setPiker];
}

-(void)setPiker {
    self.customPicker.delegate = self;
    self.customPicker.dataSource = self;
    m=0;
    firstTimeLoad = YES;
    NSDate *date = [NSDate date];
    // Get Current Year
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    
    NSString *currentyearString = [NSString stringWithFormat:@"%@",
                                   [formatter stringFromDate:date]];
    year =[currentyearString intValue];
    
    
    // Get Current  Month
    
    [formatter setDateFormat:@"MM"];
    
    currentMonthString = [NSString stringWithFormat:@"%ld",(long)[[formatter stringFromDate:date]integerValue]];
    month=[currentMonthString intValue];
    
    // Get Current  Date
    
    [formatter setDateFormat:@"dd"];
    NSString *currentDateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    
    day =[currentDateString intValue];
    
    
    yearArray = [[NSMutableArray alloc]init];
    monthMutableArray = [[NSMutableArray alloc]init];
    DaysMutableArray= [[NSMutableArray alloc]init];
    for (int i = 1970; i <= year ; i++)
    {
        [yearArray addObject:[NSString stringWithFormat:@"%d",i]];
        
    }
    // PickerView -  Months data
    monthArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12"];
    for (int i=1; i<month+1; i++) {
        [monthMutableArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
    DaysArray = [[NSMutableArray alloc]init];
    for (int i = 1; i <= 31; i++)
    {
        [DaysArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
    for (int i = 1; i <day+1; i++)
    {
        [DaysMutableArray addObject:[NSString stringWithFormat:@"%d",i]];
        
    }
    // PickerView - Default Selection as per current Date
    // 设置初始默认值
    [self.customPicker selectRow:20 inComponent:0 animated:YES];
    // [pickerView selectRow:30 inComponent:0 animated:NO];
    [self.customPicker selectRow:[monthArray indexOfObject:currentMonthString] inComponent:1 animated:YES];
    [self.customPicker selectRow:0 inComponent:2 animated:YES];
}

-(void)layoutSubviews {
    UILabel * lable1 = (UILabel *)[self.customPicker viewForRow: 20 forComponent:0];
    lable1.textColor = [UIColor redColor];
    UILabel * lable2 = (UILabel *)[self.customPicker viewForRow: [monthArray indexOfObject:currentMonthString] forComponent:1];
    lable2.textColor = [UIColor redColor];
    UILabel * lable3 = (UILabel *)[self.customPicker viewForRow: 0 forComponent:2];
    lable3.textColor = [UIColor redColor];
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 50;
}

#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    m=row;
    if (component == 0)
    {
        selectedYearRow = row;
        [self.customPicker reloadAllComponents];
    }
    else if (component == 1)
    {
        selectedMonthRow = row;
        [self.customPicker reloadAllComponents];
    }
    else if (component == 2)
    {
        selectedDayRow = row;
        [self.customPicker reloadAllComponents];
    }
    UILabel * lable1 = (UILabel *)[self.customPicker viewForRow: [pickerView selectedRowInComponent:0] forComponent:0];
    lable1.textColor = [UIColor redColor];
    UILabel * lable2 = (UILabel *)[self.customPicker viewForRow: [pickerView selectedRowInComponent:1] forComponent:1];
    lable2.textColor = [UIColor redColor];
    UILabel * lable3 = (UILabel *)[self.customPicker viewForRow: [pickerView selectedRowInComponent:2] forComponent:2];
    lable3.textColor = [UIColor redColor];
}


#pragma mark - UIPickerViewDatasource

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {
    
    // Custom View created for each component
    
    UILabel *pickerLabel = (UILabel *)view;
    
    if (pickerLabel == nil) {
        CGRect frame = CGRectMake(0.0, 0.0, 50, 60);
        pickerLabel = [[UILabel alloc] initWithFrame:frame];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:15.0f]];
    }
    
    if (component == 0)
    {
        pickerLabel.text = [NSString stringWithFormat:@"%@年", [yearArray objectAtIndex:row]]; // Year
    }
    else if (component == 1)
    {
        pickerLabel.text = [NSString stringWithFormat:@"%@月",[monthArray objectAtIndex:row]] ;  // Month
    }
    else if (component == 2)
    {
        pickerLabel.text = [NSString stringWithFormat:@"%@日",[DaysArray objectAtIndex:row]] ; // Date
        
    }
    [pickerLabel sizeToFit];
    
    return pickerLabel;
    
}


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    
    return 3;
    
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if (component == 0)
    {
        return [yearArray count];
        
    }
    else if (component == 1)
    {
        NSInteger selectRow =  [pickerView selectedRowInComponent:0];
        int n;
        n= year-1970;
        if (selectRow==n) {
            return [monthMutableArray count];
        }else
        {
            return [monthArray count];
            
        }
    }
    else
    {
        NSInteger selectRow1 =  [pickerView selectedRowInComponent:0];
        int n;
        n= year-1970;
        NSInteger selectRow =  [pickerView selectedRowInComponent:1];
        
        if (selectRow==month-1 &selectRow1==n) {
            
            return day;
            
        }else{
            
            if (selectedMonthRow == 0 || selectedMonthRow == 2 || selectedMonthRow == 4 || selectedMonthRow == 6 || selectedMonthRow == 7 || selectedMonthRow == 9 || selectedMonthRow == 11)
            {
                return 31;
            }
            else if (selectedMonthRow == 1)
            {
                int yearint = [[yearArray objectAtIndex:selectedYearRow]intValue ];
                
                if(((yearint %4==0)&&(yearint %100!=0))||(yearint %400==0)){
                    return 29;
                }
                else
                {
                    return 28; // or return 29
                }
            }
            else
            {
                return 30;
            }
        }
    }
}



-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removeFromSuperview];
}


-(void)dealloc {
    NSLog(@"PikerViewDealloc");
}

@end
